/** TRPanel */
package client.ui.panel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;

import client.ClientManager;
import client.service.AppointmentService;
import client.service.DoctorService;
import client.service.MedicalServiceService;
import client.service.NurseService;
import client.service.PatientService;
import domain.nurse.Nurse;
import domain.patient.Patient;
import domain.permissions.Permission;
import domain.records.DoctorsOrders;
import domain.records.MedicalService;
import domain.records.TreatmentRecord;
import domain.user.SystemUser;

/**
 * @author jessienewman
 * @version $Revision: 1.0 $
 */
public class TRPanel extends DefaultPanel{
	/**
	 * Field tr.
	 */
	private TreatmentRecord tr;

	/**
	 * Field center.
	 */
	private JPanel center;
	
	/**
	 * Field c.
	 */
	private GridBagConstraints c;
	
	/**
	 * Field canEdit.
	 */
	private boolean canEdit;
	
	/**
	 * Field canEditOrders.
	 */
	private boolean canEditOrders;

	/**
	 * Field patient.
	 */
	private JLabel patient, nurse, doctor;
	
	/**
	 * Field doctorText.
	 */
	/**
	 * Field nurseText.
	 */
	/**
	 * Field patientText.
	 */
	private JComboBox patientText, nurseText, doctorText;
	
	/**
	 * Field save.
	 */
	private JButton save;
	
	/**
	 * Field servicesText.
	 */
	private JList servicesText;
	
	/**
	 * Field LOGGER.
	 */
	private static final Logger LOGGER = Logger.getLogger(TRPanel.class.getName());

	/** Field diagnosisText. */
	/** Field symptomsText. */
	/** Field pulseText. */
	/** Field temperatureText. */
	/** Field heightText. */
	/** Field weightText. */
	/** Field bloodPressureText. */
	/** Field followUpText. */
	/** Field prescriptionsText. */
	private JTextField prescriptionsText, followUpText, 
	bloodPressureText, weightText, heightText,
	temperatureText, pulseText, symptomsText, diagnosisText;

	/**
	 * Constructor for TRPanel.
	 */
	public TRPanel() {
		//ClientManager.SESSION = new UserSession(0, 0);
		//Integer userId = ClientManager.SESSION.getUserId();
		center = new JPanel();
		this.add(center, BorderLayout.CENTER);
		center.setLayout(new GridBagLayout());
		center.setBackground(Color.WHITE);
		c = new GridBagConstraints();
	}

	/**
	 * Method addTreatmentRecord.
	 * @param tr TreatmentRecord
	 */
	public void addTreatmentRecord(TreatmentRecord tr) {
		canEdit = ClientManager.SESSION.hasPermission(Permission.EDIT_PATIENT);
		canEditOrders = ClientManager.SESSION.hasPermission(Permission.DOCTORS_ORDER);

		this.tr = tr;
		center.removeAll();

		//create labels

		addUsersToPanel(tr);
		
		JLabel symptoms = new JLabel(tr.getSymptoms());
		 symptomsText = new JTextField(symptoms.getText());

		JLabel height = new JLabel(tr.getHeight() + " in");
		 heightText = new JTextField(tr.getHeight() + "");

		JLabel weight = new JLabel(tr.getWeight() + " lbs");
		 weightText = new JTextField(tr.getWeight() + "");

		JLabel pulse = new JLabel(tr.getPulse() + "");
		 pulseText = new JTextField(pulse.getText());

		JLabel bloodPressure = new JLabel(tr.getBloodpressure() + "");
		 bloodPressureText = new JTextField(bloodPressure.getText());

		JLabel temperature = new JLabel(tr.getTemperature() + "");
		 temperatureText = new JTextField(temperature.getText());

		JLabel services;
		JLabel prescriptions;
		JLabel followUp;

		if (tr.getOrders() != null) {
			String serviceList = "";
			for (MedicalService ms : tr.getOrders().getService()) {
				serviceList += ms.getServiceName() + ", ";
			}
			serviceList = serviceList.length() >= 2 ? 
					serviceList.substring(0, serviceList.length() - 2) : "";
			services = new JLabel(serviceList);
			prescriptions = new JLabel(tr.getOrders().getPrescriptions());
			followUp = new JLabel(tr.getOrders().getFollowUp());
		} else {
			services = new JLabel("");
			prescriptions = new JLabel("");
			followUp = new JLabel("");
		}
		servicesText = new JList(MedicalServiceService.getAllServices().toArray());
		for (MedicalService m : tr.getOrders().getService()) {
			servicesText.setSelectedValue(m, false);
		}

		prescriptionsText = new JTextField(prescriptions.getText());
		followUpText = new JTextField(followUp.getText());

		SimpleDateFormat sdf = new SimpleDateFormat("MMMMM dd, yyyy");
		JLabel dateLabel = new JLabel("Date: ");
		JLabel date = (tr.getDate() != null) ? 
				new JLabel(sdf.format(tr.getDate())) : new JLabel("");
		//JTextField dateText = new JTextField(date.getText());

		sdf = new SimpleDateFormat("HH : mm");
		JLabel timeLabel = new JLabel("Time: ");
		JLabel time = (tr.getDate() != null) ? 
				new JLabel(sdf.format(tr.getDate())) : new JLabel("");
		//JTextField timeText = new JTextField(time.getText());

		JLabel diagnosis = new JLabel(tr.getDiagnosis());
		 diagnosisText = new JTextField(diagnosis.getText());

		//add labels
		c.gridx = 0;
		c.gridy = 0;
		c.fill = GridBagConstraints.HORIZONTAL;
		center.add(new JLabel("Patient: "), c);
		c.gridx = 1;
		center.add(canEdit ? patientText : patient, c);
		c.gridx = 0;
		c.gridy++;
		center.add(new JLabel("Doctor: "), c);
		c.gridx = 1;
		center.add(canEdit ? doctorText : doctor, c);
		c.gridx = 0;
		c.gridy++;
		center.add(new JLabel("Nurse: "), c);
		c.gridx = 1;
		center.add(canEdit ? nurseText : nurse, c);
		c.gridx = 0;
		c.gridy++;
		center.add(dateLabel, c);
		c.gridx = 1;
		center.add(date, c);
		c.gridx = 0;
		c.gridy++;
		center.add(timeLabel, c);
		c.gridx = 1;
		center.add(time, c);
		c.gridx = 0;
		c.gridy++;
		center.add(new JLabel("Symptoms: "), c);
		c.gridx = 1;
		center.add(canEdit ? symptomsText : symptoms, c);
		c.gridx = 0;
		c.gridy++;
		center.add(new JLabel("Diagnosis: "), c);
		c.gridx = 1;
		center.add(canEdit ? diagnosisText : diagnosis, c);

		c.gridx = 0;
		c.gridy++;
		center.add(new JLabel("PATIENT VITALS"), c);
		c.gridy++;
		center.add(new JLabel("Height: "), c);
		c.gridx = 1;
		center.add(canEdit ? heightText : height, c);
		c.gridx++;
		center.add(canEdit ? new JLabel("in") : new JLabel(""), c);
		c.gridx = 0;
		c.gridy++;
		center.add(new JLabel("Weight: "), c);
		c.gridx = 1;
		center.add(canEdit ? weightText : weight, c);
		c.gridx++;
		center.add(canEdit ? new JLabel("lbs") : new JLabel(""), c);
		c.gridx = 0;
		c.gridy++;
		center.add(new JLabel("Temperature: "), c);
		c.gridx = 1;
		center.add(canEdit ? temperatureText : temperature, c);
		c.gridx = 0;
		c.gridy++;
		center.add(new JLabel("Blood Pressure: "), c);
		c.gridx = 1;
		center.add(canEdit ? bloodPressureText : bloodPressure, c);
		c.gridx = 0;
		c.gridy++;
		center.add(new JLabel("Pulse: "), c);
		c.gridx = 1;
		center.add(canEdit ? pulseText : pulse, c);

		c.gridy++;
		c.gridx = 0;
		center.add(new JLabel("DOCTORS ORDERS"), c);
		c.gridy++;
		center.add(new JLabel("Prescriptions: "), c);
		c.gridx = 1;
		center.add(canEditOrders ? prescriptionsText : prescriptions, c);
		c.gridx = 0;
		c.gridy++;
		center.add(new JLabel("Services: "), c);
		c.gridx = 1;
		center.add(canEditOrders ? servicesText : services, c);
		c.gridx = 0;
		c.gridy++;
		center.add(new JLabel("Follow Up Instructions: "), c);
		c.gridx = 1;
		center.add(canEditOrders ? followUpText : followUp, c);
		c.gridy++;
		c.gridx = 0;
		save = new JButton("Save");
		save.addActionListener(new ButtonListener());
		center.add(canEdit ? save : new JLabel(""), c);

		homeButton.addActionListener(new ButtonListener());
		invoiceButton.addActionListener(new ButtonListener());
	}

	/**
	 * Method addUsersToPanel.
	 * @param tr TreatmentRecord
	 */
	private void addUsersToPanel(TreatmentRecord tr) {

		Patient pat = tr.getPatient();
		patient = new JLabel(pat.getNameLast() + ", " + 
				pat.getNameMiddle() + " " + pat.getNameFirst());
		patientText = new JComboBox(PatientService.getAllPatients().toArray());
		patientText.setRenderer(new PatientRender());

		nurse = (tr.getNurse() != null) ? 
				new JLabel(tr.getNurse().getNameLast() + ", " + 
				tr.getNurse().getNameFirst()) : new JLabel("");
		nurseText = new JComboBox(NurseService.getAllNurses().toArray());
		nurseText.setSelectedItem(tr.getNurse());
		nurseText.setRenderer(new PatientRender());

		doctor = (tr.getDoctor() != null) ? 
				new JLabel(tr.getDoctor().getNameLast() + ", " + 
				tr.getDoctor().getNameFirst()) : new JLabel("");
		doctorText = new JComboBox(DoctorService.getAllDoctors().toArray());
		doctorText.setSelectedItem(tr.getDoctor());
		doctorText.setRenderer(new PatientRender());
	}
	
	/**
	 * returns the super's toString
	
	 * @return String super's toString */
	public String toString() {
		return super.toString();
	}
	
	/**
	 * @author jessienewman
	 */
	private class ButtonListener implements ActionListener { // $codepro.audit.disable com.instantiations.assist.eclipse.analysis.audit.rule.effectivejava.alwaysOverridetoString.alwaysOverrideToString
		/**
		 * Method actionPerformed.
		 * @param event ActionEvent
		
		 * @see java.awt.event.ActionListener#actionPerformed(ActionEvent) */
		public void actionPerformed(ActionEvent event) {
			if (event.getSource().equals(save)) {
				if (canEditOrders) {
					DoctorsOrders dos = tr.getOrders();
					dos.addFollowUpInstructions(followUpText.getText());
					dos.setPrescriptions(prescriptionsText.getText());
					
					//don't even ask
					MedicalService[] ms = 
						new MedicalService[servicesText.getSelectedValues().length];
					for (int i = 0; i < ms.length ; i++) {
						ms[i] = (MedicalService) servicesText.getSelectedValues()[i];
					}
					dos.setServices(ms);
				}
				try {
					tr.setBloodpressure(Integer.parseInt(bloodPressureText.getText()));
					tr.setDiagnosis(diagnosisText.getText());
					tr.setHeight(Integer.parseInt(heightText.getText()));
					tr.setNurse((Nurse) nurseText.getSelectedItem());
					tr.setPulse(Integer.parseInt(pulseText.getText()));
					tr.setSymptoms(symptomsText.getText());
					tr.setTemperature(Integer.parseInt(temperatureText.getText()));
					tr.setWeight(Integer.parseInt(weightText.getText()));
					AppointmentService.save();
				} catch (NumberFormatException nfe) {
					LOGGER.warning("Number Format Exception: " + nfe);
				}

			}
		}
	}
	
	/**
	 * @author jessienewman
	 */
	private static class PatientRender extends JLabel implements ListCellRenderer {
		/**
		 * Method getListCellRendererComponent.
		 * @param list JList
		 * @param value Object
		 * @param index int
		 * @param isSelected boolean
		 * @param cellHasFocus boolean		
		 * @return Component  
		 * @see javax.swing.ListCellRenderer#getListCellRendererComponent(
		 * JList, Object, int, boolean, boolean) */
		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {
			if (value == null) {
				setText("");
			} else {
			setText(((SystemUser) value).getFullName());
			}
			return this;
		}
	}
	/*
	private class DoctorRender extends JLabel implements ListCellRenderer {
		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {
			setText(((Doctor)value).getFullName());
			return this;
		}	
	}*/
}


